home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / json / decoder.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  10.8 KB  |  381 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Implementation of JSONDecoder
  5. '''
  6. import re
  7. import sys
  8. from json.scanner import Scanner, pattern
  9.  
  10. try:
  11.     from _json import scanstring as c_scanstring
  12. except ImportError:
  13.     c_scanstring = None
  14.  
  15. __all__ = [
  16.     'JSONDecoder']
  17. FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
  18. NaN = float('nan')
  19. PosInf = float('inf')
  20. NegInf = float('-inf')
  21.  
  22. def linecol(doc, pos):
  23.     lineno = doc.count('\n', 0, pos) + 1
  24.     if lineno == 1:
  25.         colno = pos
  26.     else:
  27.         colno = pos - doc.rindex('\n', 0, pos)
  28.     return (lineno, colno)
  29.  
  30.  
  31. def errmsg(msg, doc, pos, end = None):
  32.     (lineno, colno) = linecol(doc, pos)
  33.     if end is None:
  34.         fmt = '{0}: line {1} column {2} (char {3})'
  35.         return fmt.format(msg, lineno, colno, pos)
  36.     (endlineno, endcolno) = linecol(doc, end)
  37.     fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
  38.     return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
  39.  
  40. _CONSTANTS = {
  41.     '-Infinity': NegInf,
  42.     'Infinity': PosInf,
  43.     'NaN': NaN,
  44.     'true': True,
  45.     'false': False,
  46.     'null': None }
  47.  
  48. def JSONConstant(match, context, c = _CONSTANTS):
  49.     s = match.group(0)
  50.     fn = getattr(context, 'parse_constant', None)
  51.     if fn is None:
  52.         rval = c[s]
  53.     else:
  54.         rval = fn(s)
  55.     return (rval, None)
  56.  
  57. pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant)
  58.  
  59. def JSONNumber(match, context):
  60.     match = JSONNumber.regex.match(match.string, *match.span())
  61.     (integer, frac, exp) = match.groups()
  62.     if frac or exp:
  63.         if not getattr(context, 'parse_float', None):
  64.             pass
  65.         fn = float
  66.         if not frac:
  67.             pass
  68.         if not exp:
  69.             pass
  70.         res = fn(integer + '' + '')
  71.     elif not getattr(context, 'parse_int', None):
  72.         pass
  73.     fn = int
  74.     res = fn(integer)
  75.     return (res, None)
  76.  
  77. pattern('(-?(?:0|[1-9]\\d*))(\\.\\d+)?([eE][-+]?\\d+)?')(JSONNumber)
  78. STRINGCHUNK = re.compile('(.*?)(["\\\\\\x00-\\x1f])', FLAGS)
  79. BACKSLASH = {
  80.     '"': u'"',
  81.     '\\': u'\\',
  82.     '/': u'/',
  83.     'b': u'\x08',
  84.     'f': u'\x0c',
  85.     'n': u'\n',
  86.     'r': u'\r',
  87.     't': u'\t' }
  88. DEFAULT_ENCODING = 'utf-8'
  89.  
  90. def py_scanstring(s, end, encoding = None, strict = True, _b = BACKSLASH, _m = STRINGCHUNK.match):
  91.     if encoding is None:
  92.         encoding = DEFAULT_ENCODING
  93.     
  94.     chunks = []
  95.     _append = chunks.append
  96.     begin = end - 1
  97.     while None:
  98.         chunk = _m(s, end)
  99.         if chunk is None:
  100.             raise ValueError(errmsg('Unterminated string starting at', s, begin))
  101.         end = chunk.end()
  102.         (content, terminator) = chunk.groups()
  103.         if content:
  104.             if not isinstance(content, unicode):
  105.                 content = unicode(content, encoding)
  106.             
  107.             _append(content)
  108.         
  109.         if terminator == '"':
  110.             break
  111.         elif terminator != '\\':
  112.             if strict:
  113.                 msg = 'Invalid control character {0!r} at'.format(terminator)
  114.                 raise ValueError(errmsg(msg, s, end))
  115.             strict
  116.             _append(terminator)
  117.             continue
  118.         
  119.         
  120.         try:
  121.             esc = s[end]
  122.         except IndexError:
  123.             raise ValueError(errmsg('Unterminated string starting at', s, begin))
  124.  
  125.         if esc != 'u':
  126.             
  127.             try:
  128.                 m = _b[esc]
  129.             except KeyError:
  130.                 msg = 'Invalid \\escape: {0!r}'.format(esc)
  131.                 raise ValueError(errmsg(msg, s, end))
  132.  
  133.             end += 1
  134.         else:
  135.             esc = s[end + 1:end + 5]
  136.             next_end = end + 5
  137.             msg = 'Invalid \\uXXXX escape'
  138.             
  139.             try:
  140.                 if len(esc) != 4:
  141.                     raise ValueError
  142.                 len(esc) != 4
  143.                 uni = int(esc, 16)
  144.                 if uni <= uni:
  145.                     pass
  146.                 elif uni <= 56319 and sys.maxunicode > 65535:
  147.                     msg = 'Invalid \\uXXXX\\uXXXX surrogate pair'
  148.                     if not s[end + 5:end + 7] == '\\u':
  149.                         raise ValueError
  150.                     s[end + 5:end + 7] == '\\u'
  151.                     esc2 = s[end + 7:end + 11]
  152.                     if len(esc2) != 4:
  153.                         raise ValueError
  154.                     len(esc2) != 4
  155.                     uni2 = int(esc2, 16)
  156.                     uni = 65536 + (uni - 55296 << 10 | uni2 - 56320)
  157.                     next_end += 6
  158.                 
  159.                 m = unichr(uni)
  160.             except ValueError:
  161.                 raise ValueError(errmsg(msg, s, end))
  162.  
  163.             end = next_end
  164.         _append(m)
  165.         continue
  166.         return (u''.join(chunks), end)
  167.  
  168. if c_scanstring is not None:
  169.     scanstring = c_scanstring
  170. else:
  171.     scanstring = py_scanstring
  172.  
  173. def JSONString(match, context):
  174.     encoding = getattr(context, 'encoding', None)
  175.     strict = getattr(context, 'strict', True)
  176.     return scanstring(match.string, match.end(), encoding, strict)
  177.  
  178. pattern('"')(JSONString)
  179. WHITESPACE = re.compile('\\s*', FLAGS)
  180.  
  181. def JSONObject(match, context, _w = WHITESPACE.match):
  182.     pairs = { }
  183.     s = match.string
  184.     end = _w(s, match.end()).end()
  185.     nextchar = s[end:end + 1]
  186.     if nextchar == '}':
  187.         return (pairs, end + 1)
  188.     if nextchar != '"':
  189.         raise ValueError(errmsg('Expecting property name', s, end))
  190.     nextchar != '"'
  191.     end += 1
  192.     encoding = getattr(context, 'encoding', None)
  193.     strict = getattr(context, 'strict', True)
  194.     iterscan = JSONScanner.iterscan
  195.     while True:
  196.         (key, end) = scanstring(s, end, encoding, strict)
  197.         end = _w(s, end).end()
  198.         if s[end:end + 1] != ':':
  199.             raise ValueError(errmsg('Expecting : delimiter', s, end))
  200.         s[end:end + 1] != ':'
  201.         end = _w(s, end + 1).end()
  202.         
  203.         try:
  204.             (value, end) = iterscan(s, idx = end, context = context).next()
  205.         except StopIteration:
  206.             nextchar == '}'
  207.             nextchar == '}'
  208.             raise ValueError(errmsg('Expecting object', s, end))
  209.         except:
  210.             nextchar == '}'
  211.  
  212.         pairs[key] = value
  213.         end = _w(s, end).end()
  214.         nextchar = s[end:end + 1]
  215.         end += 1
  216.         if nextchar == '}':
  217.             break
  218.         
  219.         if nextchar != ',':
  220.             raise ValueError(errmsg('Expecting , delimiter', s, end - 1))
  221.         nextchar != ','
  222.         end = _w(s, end).end()
  223.         nextchar = s[end:end + 1]
  224.         end += 1
  225.         if nextchar != '"':
  226.             raise ValueError(errmsg('Expecting property name', s, end - 1))
  227.         nextchar != '"'
  228.     object_hook = getattr(context, 'object_hook', None)
  229.     if object_hook is not None:
  230.         pairs = object_hook(pairs)
  231.     
  232.     return (pairs, end)
  233.  
  234. pattern('{')(JSONObject)
  235.  
  236. def JSONArray(match, context, _w = WHITESPACE.match):
  237.     values = []
  238.     s = match.string
  239.     end = _w(s, match.end()).end()
  240.     nextchar = s[end:end + 1]
  241.     if nextchar == ']':
  242.         return (values, end + 1)
  243.     iterscan = JSONScanner.iterscan
  244.     while True:
  245.         
  246.         try:
  247.             (value, end) = iterscan(s, idx = end, context = context).next()
  248.         except StopIteration:
  249.             nextchar == ']'
  250.             nextchar == ']'
  251.             raise ValueError(errmsg('Expecting object', s, end))
  252.         except:
  253.             nextchar == ']'
  254.  
  255.         values.append(value)
  256.         end = _w(s, end).end()
  257.         nextchar = s[end:end + 1]
  258.         end += 1
  259.         if nextchar == ']':
  260.             break
  261.         
  262.         if nextchar != ',':
  263.             raise ValueError(errmsg('Expecting , delimiter', s, end))
  264.         nextchar != ','
  265.         end = _w(s, end).end()
  266.     return (values, end)
  267.  
  268. pattern('\\[')(JSONArray)
  269. ANYTHING = [
  270.     JSONObject,
  271.     JSONArray,
  272.     JSONString,
  273.     JSONConstant,
  274.     JSONNumber]
  275. JSONScanner = Scanner(ANYTHING)
  276.  
  277. class JSONDecoder(object):
  278.     '''Simple JSON <http://json.org> decoder
  279.  
  280.     Performs the following translations in decoding by default:
  281.  
  282.     +---------------+-------------------+
  283.     | JSON          | Python            |
  284.     +===============+===================+
  285.     | object        | dict              |
  286.     +---------------+-------------------+
  287.     | array         | list              |
  288.     +---------------+-------------------+
  289.     | string        | unicode           |
  290.     +---------------+-------------------+
  291.     | number (int)  | int, long         |
  292.     +---------------+-------------------+
  293.     | number (real) | float             |
  294.     +---------------+-------------------+
  295.     | true          | True              |
  296.     +---------------+-------------------+
  297.     | false         | False             |
  298.     +---------------+-------------------+
  299.     | null          | None              |
  300.     +---------------+-------------------+
  301.  
  302.     It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
  303.     their corresponding ``float`` values, which is outside the JSON spec.
  304.     '''
  305.     _scanner = Scanner(ANYTHING)
  306.     __all__ = [
  307.         '__init__',
  308.         'decode',
  309.         'raw_decode']
  310.     
  311.     def __init__(self, encoding = None, object_hook = None, parse_float = None, parse_int = None, parse_constant = None, strict = True):
  312.         '''``encoding`` determines the encoding used to interpret any ``str``
  313.         objects decoded by this instance (utf-8 by default).  It has no
  314.         effect when decoding ``unicode`` objects.
  315.  
  316.         Note that currently only encodings that are a superset of ASCII work,
  317.         strings of other encodings should be passed in as ``unicode``.
  318.  
  319.         ``object_hook``, if specified, will be called with the result of
  320.         every JSON object decoded and its return value will be used in
  321.         place of the given ``dict``.  This can be used to provide custom
  322.         deserializations (e.g. to support JSON-RPC class hinting).
  323.  
  324.         ``parse_float``, if specified, will be called with the string
  325.         of every JSON float to be decoded. By default this is equivalent to
  326.         float(num_str). This can be used to use another datatype or parser
  327.         for JSON floats (e.g. decimal.Decimal).
  328.  
  329.         ``parse_int``, if specified, will be called with the string
  330.         of every JSON int to be decoded. By default this is equivalent to
  331.         int(num_str). This can be used to use another datatype or parser
  332.         for JSON integers (e.g. float).
  333.  
  334.         ``parse_constant``, if specified, will be called with one of the
  335.         following strings: -Infinity, Infinity, NaN, null, true, false.
  336.         This can be used to raise an exception if invalid JSON numbers
  337.         are encountered.
  338.  
  339.         '''
  340.         self.encoding = encoding
  341.         self.object_hook = object_hook
  342.         self.parse_float = parse_float
  343.         self.parse_int = parse_int
  344.         self.parse_constant = parse_constant
  345.         self.strict = strict
  346.  
  347.     
  348.     def decode(self, s, _w = WHITESPACE.match):
  349.         '''
  350.         Return the Python representation of ``s`` (a ``str`` or ``unicode``
  351.         instance containing a JSON document)
  352.  
  353.         '''
  354.         (obj, end) = self.raw_decode(s, idx = _w(s, 0).end())
  355.         end = _w(s, end).end()
  356.         if end != len(s):
  357.             raise ValueError(errmsg('Extra data', s, end, len(s)))
  358.         end != len(s)
  359.         return obj
  360.  
  361.     
  362.     def raw_decode(self, s, **kw):
  363.         '''Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
  364.         with a JSON document) and return a 2-tuple of the Python
  365.         representation and the index in ``s`` where the document ended.
  366.  
  367.         This can be used to decode a JSON document from a string that may
  368.         have extraneous data at the end.
  369.  
  370.         '''
  371.         kw.setdefault('context', self)
  372.         
  373.         try:
  374.             (obj, end) = self._scanner.iterscan(s, **kw).next()
  375.         except StopIteration:
  376.             raise ValueError('No JSON object could be decoded')
  377.  
  378.         return (obj, end)
  379.  
  380.  
  381.